/**
 * 文件上传组件
 */

import React, { useCallback, useState } from 'react';
import { Upload, message, Progress } from 'antd';
import { InboxOutlined, FileExcelOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { themeConfig } from '../../theme/themeConfig';
import { UploadFile as UploadFileType } from '../../types';
import { createUploadFile, formatFileSize, validateFileType, validateFileSize } from '../../utils/fileUtils';

interface FileUploadProps {
  onFileSelect: (file: UploadFileType) => void;
  isUploading: boolean;
  accept?: string;
  maxSize?: number;
}

const UploadContainer = styled.div`
  .upload-dragger {
    border: 2px dashed ${themeConfig.colors.border};
    border-radius: ${themeConfig.borderRadius.medium};
    background-color: ${themeConfig.colors.backgroundLight};
    transition: all ${themeConfig.transitions.duration} ${themeConfig.transitions.easing};
    
    &:hover {
      border-color: ${themeConfig.colors.primary};
      background-color: #FFF2E8;
    }
    
    &.ant-upload-drag-hover {
      border-color: ${themeConfig.colors.primary};
      background-color: #FFF2E8;
    }
  }
  
  .upload-icon {
    font-size: 48px;
    color: ${themeConfig.colors.primary};
    margin-bottom: ${themeConfig.spacing.md};
  }
  
  .upload-text {
    font-size: ${themeConfig.typography.fontSize.body};
    color: ${themeConfig.colors.text};
    margin-bottom: ${themeConfig.spacing.sm};
  }
  
  .upload-hint {
    font-size: ${themeConfig.typography.fontSize.caption};
    color: ${themeConfig.colors.textSecondary};
  }
  
  .file-info {
    margin-top: ${themeConfig.spacing.md};
    padding: ${themeConfig.spacing.md};
    background-color: ${themeConfig.colors.background};
    border-radius: ${themeConfig.borderRadius.small};
    border: 1px solid ${themeConfig.colors.border};
  }
  
  .file-name {
    display: flex;
    align-items: center;
    gap: ${themeConfig.spacing.sm};
    font-weight: ${themeConfig.typography.fontWeight.medium};
    color: ${themeConfig.colors.text};
    margin-bottom: ${themeConfig.spacing.xs};
  }
  
  .file-size {
    font-size: ${themeConfig.typography.fontSize.caption};
    color: ${themeConfig.colors.textSecondary};
  }
`;

export const FileUpload: React.FC<FileUploadProps> = ({
  onFileSelect,
  isUploading,
  accept = '.xlsx',
  maxSize = 10,
}) => {
  const [uploadProgress, setUploadProgress] = useState(0);
  const [selectedFile, setSelectedFile] = useState<UploadFileType | null>(null);

  const handleFileChange = useCallback((info: any) => {
    const { file } = info;
    
    if (file.status === 'uploading') {
      setUploadProgress(file.percent || 0);
    }
    
    if (file.status === 'done') {
      setUploadProgress(100);
      const uploadFile = createUploadFile(file.originFileObj);
      setSelectedFile(uploadFile);
      onFileSelect(uploadFile);
      message.success('文件上传成功！');
    }
    
    if (file.status === 'error') {
      message.error('文件上传失败！');
    }
  }, [onFileSelect]);


  const handleFileSelect = useCallback((file: File) => {
    // 先验证文件
    if (!validateFileType(file)) {
      message.error('只支持上传 .xlsx 格式的Excel文件！');
      return;
    }
    
    if (!validateFileSize(file, maxSize)) {
      message.error(`文件大小不能超过 ${maxSize}MB！`);
      return;
    }
    
    // 验证通过，创建上传文件对象
    const uploadFile = createUploadFile(file);
    setSelectedFile(uploadFile);
    onFileSelect(uploadFile);
    message.success('文件选择成功！');
  }, [maxSize, onFileSelect]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    const files = Array.from(e.dataTransfer.files);
    
    if (files.length > 0) {
      handleFileSelect(files[0]);
    }
  }, [handleFileSelect]);


  return (
    <UploadContainer>
      <Upload.Dragger
        name="file"
        multiple={false}
        accept={accept}
        showUploadList={false}
        beforeUpload={(file) => {
          handleFileSelect(file);
          return false; // 阻止默认上传行为
        }}
        onChange={handleFileChange}
        disabled={isUploading}
        onDrop={handleDrop}
      >
        <div className="upload-dragger">
          <InboxOutlined className="upload-icon" />
          <div className="upload-text">
            {isUploading ? '正在上传...' : '点击或拖拽文件到此区域上传'}
          </div>
          <div className="upload-hint">
            支持 .xlsx 格式，文件大小不超过 {maxSize}MB
          </div>
        </div>
      </Upload.Dragger>
      
      {isUploading && (
        <Progress
          percent={uploadProgress}
          status="active"
          strokeColor={themeConfig.colors.primary}
          style={{ marginTop: themeConfig.spacing.md }}
        />
      )}
      
      {selectedFile && !isUploading && (
        <div className="file-info">
          <div className="file-name">
            <FileExcelOutlined />
            {selectedFile.name}
          </div>
          <div className="file-size">
            文件大小: {formatFileSize(selectedFile.size)}
          </div>
        </div>
      )}
    </UploadContainer>
  );
};
